<?php

require_once dirname(__FILE__).'/../lib/grupoGeneratorConfiguration.class.php';

class grupoActions extends autoGrupoActions
{

	public function getCredential()
	{
		return 'Grupo';
	}

	public function executeUsers(sfWebRequest $request)
	{
		$id = $request->getParameter('id');
		$table = sfGuardGroupTable::getInstance();

		$this->group = $table->find($id);
		$this->forward404Unless($this->group);

		$this->pager = $this->configuration->getPager('sfGuardUserGroup');

		$query = $table->getUsersQuery($id);

		$this->pager->setQuery($query);

		if ($request->hasParameter('page'))
			$this->pager->setPage($request->getParameter('page'));
		else
			$this->pager->setPage(0);

		$this->pager->init();

		$this->setTemplate('users');
	}
	
	public function executeAddUser(sfWebRequest $request)
	{
		$user_group = new sfGuardUserGroup();
		$user_group->group_id = $request->getParameter('id');

		$this->form = new sfGuardUserGroupForm($user_group);

		if ($request->isMethod('post'))
			$this->createUser($request, $this->form);
	}

	private function createUser(sfWebRequest $request, $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

		if ($form->isValid())
		{
			$values = $form->getValues();
			$notice = 'El usuario se ha agregado correctamente.';

			try {
				$user_group = $form->save();
			} catch (Doctrine_Validator_Exception $e) {
				$errorStack = $form->getObject()->getErrorStack();

				$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?	's' : null) . " with validation errors: ";
				foreach ($errorStack as $field => $errors) {
					$message .= "$field (" . implode(", ", $errors) . "), ";
				}
				$message = trim($message, ', ');

				$this->getUser()->setFlash('error', $message);
				return sfView::SUCCESS;
			}

			$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $user_group)));

			if ($request->hasParameter('_save_and_add'))
			{
				$this->getUser()->setFlash('notice', $notice.' Ahora puede agregar otro');

				$this->redirect('@grupo_addUser?id=' . $user_group->group_id);
			}
			else
			{
				$this->getUser()->setFlash('notice', $notice);
				$this->redirect('@grupo_users?id=' . $user_group->group_id);
			}
		}
		else
		{
			$this->getUser()->setFlash('error', 'El usuario no se ha agregado porque se ha producido algún error.', false);
		}
	}

	public function executeDeleteUser(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$group_id = $request->getParameter('id');
		$user_id = $request->getParameter('user');

		$user_group = sfGuardGroupTable::getInstance()->getUserGroup($user_id, $group_id);

		if ($user_group->delete())
			$this->getUser()->setFlash('notice','El usuario ha sido ha sido excluido del grupo');

		$this->redirect('@grupo_users?id=' . $group_id);
	}

	public function executeBatchUsers(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$group_id = $request->getParameter('group_id');

		if (!$ids = $request->getParameter('ids'))
		{
			$this->getUser()->setFlash('error', 'Debe seleccionar al menos un usuario.');

			$this->redirect('@grupo_users?id=' . $group_id);
		}

		if (!$action = $request->getParameter('batch_action'))
		{
			$this->getUser()->setFlash('error', 'Seleccione la acción que quiera ejecutar sobre los usuarios seleccionados.');

			$this->redirect('@grupo_users?id=' . $group_id);
		}

		if (!$this->getUser()->hasCredential($this->configuration->getCredentials($action)))
		{
			$this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
		}

		try
		{
			$method = 'execute' . ucfirst($action);
			$this->$method($request);
		}
		catch (sfValidatorError $e)
		{
			$this->getUser()->setFlash('error', 'No se pudo realizar la acción');
		}
		
		$this->redirect('@grupo_users?id=' . $group_id);
	}

	public function executeBatchDeleteUsers(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$ids = $request->getParameter('ids');
		$group_id = $request->getParameter('group_id');

		$records = sfGuardGroupTable::getInstance()->getUsersList($group_id, $ids);

		foreach ($records as $record)
		{
			$record->delete();
		}

		$this->getUser()->setFlash('notice', 'Los usuarios seleccionados se han excluido del grupo.');
		$this->redirect('@grupo_users?id=' . $group_id);
	}

	public function executePermissions(sfWebRequest $request)
	{
		$id = $request->getParameter('id');
		$table = sfGuardGroupTable::getInstance();

		$this->group = $table->find($id);
		$this->forward404Unless($this->group);

		$this->pager = $this->configuration->getPager('sfGuardGroupPermission');

		$query = $table->getPermissionsQuery($id);

		$this->pager->setQuery($query);
		
		if ($request->hasParameter('page'))
			$this->pager->setPage($request->getParameter('page'));
		else
			$this->pager->setPage(0);

		$this->pager->init();

		$this->setTemplate('permissions');
	}

	public function executeAddPermission(sfWebRequest $request)
	{
		$group_permission = new sfGuardGroupPermission();
		$group_permission->group_id = $request->getParameter('id');

		$this->form = new sfGuardGroupPermissionForm($group_permission);
		
		if ($request->isMethod('post'))
			$this->createPermission($request, $this->form);
	}

	private function createPermission(sfWebRequest $request, $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

		if ($form->isValid())
		{
			$values = $form->getValues();

			$notice = 'El permiso se ha agregado correctamente.';

			try {
				$permission_group = $form->save();
			} catch (Doctrine_Validator_Exception $e) {
				$errorStack = $form->getObject()->getErrorStack();

				$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?	's' : null) . " with validation errors: ";
				foreach ($errorStack as $field => $errors) {
					$message .= "$field (" . implode(", ", $errors) . "), ";
				}
				$message = trim($message, ', ');

				$this->getUser()->setFlash('error', $message);
				return sfView::SUCCESS;
			}

			$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $permission_group)));

			if ($request->hasParameter('_save_and_add'))
			{
				$this->getUser()->setFlash('notice', $notice.' Ahora puede agregar otro');

				$this->redirect('@grupo_addPermission?id=' . $permission_group->group_id);
			}
			else
			{
				$this->getUser()->setFlash('notice', $notice);
				$this->redirect('@grupo_permissions?id=' . $permission_group->group_id);
			}
		}
		else
		{
			$this->getUser()->setFlash('error', 'El permiso no se ha agregado porque se ha producido algún error.', false);
		}
	}

	public function executeDeletePermission(sfWebRequest $request)
	{
		$request->checkCSRFProtection();
		
		$group_id = $request->getParameter('id');
		$permission_id = $request->getParameter('permission_id');
		
		$permission_group = sfGuardGroupTable::getInstance()->getGroupPermission($group_id, $permission_id);

		if ($permission_group->delete())
			$this->getUser()->setFlash('notice','El permiso ha sido excluido del grupo');

		$this->redirect('@grupo_permissions?id=' . $group_id);
	}
	
	public function executeBatchPermissions(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$group_id = $request->getParameter('group_id');

		if (!$ids = $request->getParameter('ids'))
		{
			$this->getUser()->setFlash('error', 'Debe seleccionar al menos un permiso.');

			$this->redirect('@grupo_permissions?id=' . $group_id);
		}

		if (!$action = $request->getParameter('batch_action'))
		{
			$this->getUser()->setFlash('error', 'Seleccione la acción que quiera ejecutar sobre los permisos seleccionados.');

			$this->redirect('@grupo_permissions?id=' . $group_id);
		}

		if (!$this->getUser()->hasCredential($this->configuration->getCredentials($action)))
		{
			$this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
		}
		
		try
		{
			$method = 'execute' . ucfirst($action);
			$this->$method($request);
		}
		catch (sfValidatorError $e)
		{
			$this->getUser()->setFlash('error', 'No se pudo realizar la acción');
		}

		$this->redirect('@grupo_permissions?id=' . $group_id);
	}

	public function executeBatchDeletePermissions(sfWebRequest $request)
	{
		$ids = $request->getParameter('ids');
		$group_id = $request->getParameter('group_id');

		$records = sfGuardGroupTable::getInstance()->getPermissionsList($group_id, $ids);

		foreach ($records as $record)
		{
			$record->delete();
		}

		$this->getUser()->setFlash('notice', 'Los permisos seleccionados se han excluido del grupo.');
		$this->redirect('@grupo_permissions?id=' . $group_id);
	}

}
